﻿using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace Citi.SecurityHelper
{
    public class Encryption
    {
        static byte[] bytes = ASCIIEncoding.ASCII.GetBytes("0v3rH34D");
        
        public static string Encrypt(string passwordString)
        {
            if (String.IsNullOrEmpty(passwordString))
            {
                throw new ArgumentNullException
                       ("The string which needs to be encrypted can not be null.");
            }

            var cryptoProvider = new DESCryptoServiceProvider();
            var memoryStream = new MemoryStream();
            var cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(bytes, bytes), CryptoStreamMode.Write);

            var writer = new StreamWriter(cryptoStream);

            writer.Write(passwordString);
            writer.Flush();
            cryptoStream.FlushFinalBlock();
            writer.Flush();

            return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
        }

        internal static string Decrypt(string cryptedString)
        {
            if (String.IsNullOrEmpty(cryptedString))
            {
                throw new ArgumentNullException
                   ("The string which needs to be decrypted can not be null.");
            }
            var cryptoProvider = new DESCryptoServiceProvider();
            var memoryStream = new MemoryStream(Convert.FromBase64String(cryptedString));
            var cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateDecryptor(bytes, bytes), CryptoStreamMode.Read);
            var reader = new StreamReader(cryptoStream);

            return reader.ReadToEnd();
        }
    }
}
